import React from 'react';
import dva, { connect, ConnectedRouter } from './dva';
import { Router, Route, Link, routerRedux } from 'dva/router';

// dva是一个函数，执行它可以得到一个app实例
const app = dva();
// model方法定义一个模型
app.model({
	namespace: 'counter',
	state: { number: 0 },
	reducers: {
		add(state) {
			return { number: state.number + 1 };
		}
	},
	effects: {
		// action动作，effects = redux/effects（take, put, ...）
		*asyncAdd(action, { call, put, select }) {
			yield call(delay, 1000);
			yield put({ type: 'add' }); // 不用加命名空间前缀
			let state = yield select(state => state.counter);
			console.log('state', state);
		},
		*goto({ payload }, { put }) {
			// push是一个actionCreator，执行会返回一个action = {type: 'CALL_HISTORY_METHOD', payload: {method: 'push'}}
			yield put(routerRedux.push(payload));
		}
	}
})

function Counter(props) {
	return (
		<div>
			<p>{props.number}</p>
			<button onClick={() => props.dispatch({ type: 'counter/add' })}>+</button>
			<button onClick={() => props.dispatch({ type: 'counter/asyncAdd' })}>async +</button>
			<button onClick={() => props.dispatch({ type: 'counter/goto', payload: '/' })}>跳转到home</button>
		</div>
	)
}

function delay(ms) {
	return new Promise(resolve => {
		setTimeout(resolve, ms);
	})
}

const ConnectedCounter = connect(state => state.counter)(Counter);
const Home = () => <div>home</div>
app.router((api) => (
	<ConnectedRouter history={api.history}>
		<>
			<Link to="/">home</Link>
			<Link to="/counter">counter</Link>
			<Route path="/" exact="true" component={Home}></Route>
			<Route path="/counter" component={ConnectedCounter}></Route>
		</>
	</ConnectedRouter>
));

app.start('#root');

